const fs = require('fs')
const path = require('path')
const cheerio = require('cheerio')
const request = require('request')

fs.readdir(path.join(__dirname, './pages'), (err, filenames) => {
  // 循环每一个页面
  filenames.forEach(filename => {
    // 每个页面的完整路径
    const fullPath = path.join(__dirname, './pages', filename)
    fs.readFile(fullPath, 'utf-8', (err, html) => {
      const $ = cheerio.load(html)
      $('#table1')
        .find('td')
        .each((i, item) => {
          const img = $(item).find('img')

          let word = ''
          let imageSrc = 'http://www.hydcd.com/cy/fkccy/' + $(img).attr('src')

          // 处理成语
          if ($(img).attr('alt')) {
            word = $(img).attr('alt')
          } else {
            word = $(item)
              .find('a')
              .text()
          }
          if (word.length > 4) {
            word = word.substr(4)
          }

          // console.log(word + ' --- ' + imageSrc)

          // request(imageSrc).pipe(
          //   fs.createWriteStream(path.join(__dirname, './pages', word + '.png'))
          // )
        })
    })
  })
})
